package com.xiaoy.core.workflow.engine.activiti.activiti5;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Service;

import com.xiaoy.core.workflow.engine.exception.BPMEngineException;
import com.xiaoy.core.workflow.simple.entity.InstanceProcessVO;
import com.xiaoy.core.workflow.simple.entity.ProcessDefine;
import com.xiaoy.core.workflow.simple.entity.ProcessInfo;
import com.xiaoy.core.workflow.simple.entity.ProcessInstantiate;
import com.xiaoy.core.workflow.simple.entity.ProcessTask;

@Service("workFlowActiviti5Impl")
public class WorkFlowActiviti5Impl extends EngineActiviti5{

	
	
	@Override
	public void delete(String id) {
		
	}

	@Override
	public ProcessDefine getProcessDefineById(String id) {
		
		return null;
	}

	@Override
	public List<ProcessDefine> getAllProcessDefinitions() throws BPMEngineException{
		
		List<ProcessDefinition> processDefinitions = repositoryService.createProcessDefinitionQuery().list();
		
		
		List<ProcessDefine> infos = new ArrayList<ProcessDefine>();
		ProcessDefine info = null;
		for (ProcessDefinition define : processDefinitions) {
			info = new ProcessDefine();
			
			info.setDeploymentId(define.getDeploymentId());
			info.setName(define.getName());
			info.setId(define.getId());
			info.setKey(define.getKey());
			infos.add(info);
			info = null;
		}
		
		return infos;
	}

	@Override
	public ProcessInstantiate createProcessInstanceById(InstanceProcessVO vo) throws BPMEngineException {
		
		ProcessInstantiate instance = new ProcessInstantiate();
		ProcessInstance processInstance=this.runtimeService.startProcessInstanceByKey(vo.getKey());
		instance.setId(processInstance.getProcessInstanceId());
		
		return instance;
	}

	@Override
	public ProcessDefine DefineProcess(Object...objs) throws BPMEngineException{
		
		DeploymentBuilder builder = repositoryService.createDeployment();
		builder.addInputStream(objs[0].toString(), (InputStream) objs[1]);
//		builder = builder.addClasspathResource(objs[0].toString());
		Deployment deployment = builder.deploy();
		System.out.println("DefineProcess:"+deployment.getId()+""+deployment.getName());
		
		ProcessDefine define = new ProcessDefine();
		
		
		return define;
	}

	
	
	
	
	@Override
	public ProcessTask getTaskByUsername(String user) {
		
		// 使用taskService根据用户ID获取候选任务
		List<Task> tasks = taskService.createTaskQuery()
		.taskAssignee(user)
		.orderByTaskCreateTime()
		.desc()
		.list();
		return null;
	}
	
	
	
	
	

}
